package com.dzm.xgb.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dzm.common.exception.Assert;
import com.dzm.common.result.ResponseEnum;
import com.dzm.xgb.core.enums.LendStatusEnum;
import com.dzm.xgb.core.enums.TransTypeEnum;
import com.dzm.xgb.core.enums.UserBindEnum;
import com.dzm.xgb.core.hfb.FormHelper;
import com.dzm.xgb.core.hfb.HfbConst;
import com.dzm.xgb.core.hfb.RequestHelper;
import com.dzm.xgb.core.pojo.entity.Lend;
import com.dzm.xgb.core.pojo.entity.LendItem;
import com.dzm.xgb.core.mapper.LendItemMapper;
import com.dzm.xgb.core.pojo.entity.TransFlow;
import com.dzm.xgb.core.pojo.entity.UserInfo;
import com.dzm.xgb.core.pojo.vo.InvestVO;
import com.dzm.xgb.core.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dzm.xgb.core.utils.LendNoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 标的出借记录表 服务实现类
 * </p>
 *
 * @author Dzm
 * @since 2024-08-27
 */
@Service
public class LendItemServiceImpl extends ServiceImpl<LendItemMapper, LendItem> implements LendItemService {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private TransFlowService transFlowService;

    @Autowired
    private LendService lendService;

    @Autowired
    private UserAccountService userAccountService;

    @Override
    public String commitInvest(InvestVO vo) {
        //第一部分：对标的资金及用户资金进行校验
        Long investUserId = vo.getInvestUserId();
        Long lendId = vo.getLendId();
        //判断当前标的是否在募资
        Lend lend = lendService.getById(lendId);
        Assert.isTrue(lend.getStatus().equals(LendStatusEnum.INVEST_RUN.getStatus()), ResponseEnum.LEND_FULL_SCALE_ERROR);
        //判断当前投资资金是否大于标的所需资金
        BigDecimal needAmount = lend.getAmount().subtract(lend.getInvestAmount());
        Assert.isTrue(needAmount.compareTo(new BigDecimal(vo.getInvestAmount())) >= 0, ResponseEnum.LEND_FULL_SCALE_ERROR);
        //判断当前投标人有相应资金
        BigDecimal userAccount = userAccountService.getAccount(investUserId);
        Assert.isTrue(userAccount.compareTo(new BigDecimal(vo.getInvestAmount())) >= 0, ResponseEnum.USER_AMOUNT_LESS_ERROR);

        //第二部分：构建标的项
        LendItem lendItem = new LendItem();
        String lendNo = LendNoUtils.getLendNo();
        lendItem.setLendItemNo(lendNo);
        lendItem.setLendId(lendId);
        lendItem.setInvestAmount(new BigDecimal(vo.getInvestAmount()));
        lendItem.setLendEndDate(lend.getLendEndDate());
        lendItem.setLendStartDate(lend.getLendStartDate());
        //获取预期收益
        BigDecimal expectAmount = lendService.getInterestCount(new BigDecimal(vo.getInvestAmount()),
                lend.getLendYearRate(),
                lend.getPeriod(),
                lend.getReturnMethod());
        lendItem.setExpectAmount(expectAmount);
        lendItem.setInvestName(vo.getInvestName());
        lendItem.setInvestTime(LocalDateTime.now());
        lendItem.setLendYearRate(lend.getLendYearRate());
        lendItem.setInvestUserId(investUserId);
        lendItem.setRealAmount(new BigDecimal(0));
        lendItem.setStatus(0);   //默认状态

        this.save(lendItem);

        //第三部分：表单生成
        //投资人
        UserInfo investUser = userInfoService.getById(investUserId);
        //借款人
        UserInfo borrower = userInfoService.getById(lend.getUserId());
        Map<String, Object> param = new HashMap<>();
        param.put("agentId", HfbConst.AGENT_ID);
        param.put("voteBindCode", investUser.getBindCode());    //投资人绑定协议号
        param.put("benefitBindCode", borrower.getBindCode());   //借款人绑定协议号
        param.put("agentProjectCode", lend.getLendNo());        //项目号
        param.put("agentProjectName", lend.getTitle());
        param.put("agentBillNo", lendNo);                       //订单号
        param.put("voteAmt", vo.getInvestAmount());
        param.put("votePrizeAmt", 0);
        param.put("voteFeeAmt", 0);
        param.put("projectAmt", lend.getAmount());
        param.put("note", "");
        param.put("notifyUrl", HfbConst.INVEST_NOTIFY_URL);
        param.put("returnUrl", HfbConst.INVEST_RETURN_URL);
        param.put("timestamp", RequestHelper.getTimestamp());
        param.put("sign", RequestHelper.getSign(param));

        String formStr = FormHelper.buildForm(HfbConst.INVEST_URL, param);
        return formStr;
    }

    /**
     * 投资异步回调
     * 1. 修改投资人资金及冻结资金
     * 2. 修改lendItem状态为已支付
     * 3. 修改标的信息投资金额和投资人数
     * 4. 添加交易流水
     * @param map
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String lendItemNotify(Map<String, Object> map) {
        //幂等性判断
        String transNo = (String) map.get("agentBillNo");
        TransFlow transFlow = transFlowService.getOne(new LambdaQueryWrapper<TransFlow>()
                .eq(TransFlow::getTransNo, transNo));
        if(transFlow != null) {
            //已产生流水
            return "success";
        }

        //修改投资用户资金
        BigDecimal voteAmt = new BigDecimal(map.get("voteAmt").toString());
        String voteBindCode = (String) map.get("voteBindCode");
        userAccountService.updateUserAccount(voteBindCode, voteAmt.negate(), voteAmt);

        //修改lendItem状态
        LendItem lendItem = this.getOne(new LambdaQueryWrapper<LendItem>()
                .eq(LendItem::getLendItemNo, transNo));
        lendItem.setStatus(1);
        this.updateById(lendItem);

        //修改标的信息
        Lend lend = lendService.getById(lendItem.getLendId());
        lend.setInvestNum(lend.getInvestNum() + 1);
        lend.setInvestAmount(lend.getInvestAmount().add(voteAmt));
        lendService.updateById(lend);

        //添加交易流水
        transFlow = new TransFlow();
        transFlow.setUserName(lendItem.getInvestName());
        transFlow.setTransType(TransTypeEnum.INVEST_LOCK.getTransType());
        transFlow.setTransTypeName(TransTypeEnum.INVEST_LOCK.getTransTypeName());
        transFlow.setTransNo(transNo);
        transFlow.setTransAmount(voteAmt);
        transFlow.setUserId(lendItem.getInvestUserId());
        transFlow.setMemo("投资项目编号：" + lend.getLendNo() + "，项目名称：" + lend.getTitle());
        transFlow.setUserName(lendItem.getInvestName());
        transFlowService.save(transFlow);

        return "success";
    }

    @Override
    public List<LendItem> getLendItems(Long id, int status) {
        List<LendItem> list = this.list(new LambdaQueryWrapper<LendItem>()
                .eq(LendItem::getLendId, id)
                .eq(LendItem::getStatus, status));
        return list;
    }

    @Override
    public List<LendItem> getLendItemList(Long id) {
        List<LendItem> list = this.list(new LambdaQueryWrapper<LendItem>()
                .eq(LendItem::getLendId, id));
        return list;
    }
}
